import { ref, onUnmounted } from "vue";
import { ZegoExpressEngine } from "zego-express-engine-webrtc";
// import mitt from "mitt"; // 轻量事件发射器

interface ZegoStream {
  streamID: string;
  user: {
    userID: string;
    userName: string;
  };
  extraInfo?: string;
}

export default function useZego() {
  const appID = 152514410; // 替换为你的 Zego AppID
  const server = "wss://webliveroom433619208-api.coolzcloud.com/ws"; // 测试环境服务器
  // 测试用token
  const token =
    "04AAAAAGf42IgADJmObc+PkgCfEd8dvwCuspnvO2PY1D49zj96b0ITGBhA6AulD/JY0zZa9pSjzqvk1Ujhvc6SKKfiwhz89zBc01VomBDmAp70MIRGuju0XTOLgnSM+YPP/f+hIFb5+fb3QOjaIu9uc9/WLn2UBOPi2ZSGo/TDwpYtNhgmoMu43GPmbRHBQ56qStF9j3VMUa0ReXfxl1a/NpfIn3MiSjrHQG14o4HEJVihCW+eO/dJNCbnXi5hKQz+ktYVmYdmAQ==";

  const zego = ref();
  const localStream = ref<MediaStream | null>(null);
  const remoteStream = ref<string | null>(null);
  const userID = ref("");
  const userName = ref("");
  const roomID = ref("");
  const isInRoom = ref(false);
  const isPublishing = ref(false);
  const isInit = ref(false);

  // 生成token (实际项目中应从服务器获取)
  const generateToken = async (roomID: string, userID: string) => {
    console.log(roomID, userID);
    // 这里应该替换为你的服务器接口调用
    return token;
  };

  // 初始化 SDK
  const initSDK = (id: string, name: string) => {
    userID.value = id;
    userName.value = name;
    zego.value = new ZegoExpressEngine(appID, server);
    isInit.value = true;
    console.log("ZEGO SDK initialized");
    // 监听事件
    setupEventHandlers();
  };

  // 设置事件处理器
  const setupEventHandlers = () => {
    zego.value.on(
      "roomStateChanged",
      (
        roomID: string | undefined,
        state: boolean,
        errorCode: unknown,
        extendedData: unknown
      ) => {
        console.log("房间状态变化:", roomID, state, errorCode, extendedData);
      }
    );

    zego.value.on(
      "roomUserUpdate",
      (roomID: string | undefined, updateType: unknown, userList: unknown) => {
        console.log("房间用户更新:", roomID, updateType, userList);
      }
    );

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    zego.value.on(
      "roomStreamUpdate",
      async (
        roomID: string | undefined,
        updateType: unknown,
        streamList: ZegoStream[]
      ) => {
        console.log("房间流更新:", roomID, updateType, streamList);
        if (updateType === "ADD") {
          // 有新的流加入，开始播放
          remoteStream.value = streamList[0].streamID;
          if (remoteStream.value) await playRemoteStream(remoteStream.value);
        } else if (updateType === "DELETE") {
          // 流被删除，停止播放
          stopPlayStream(streamList[0].streamID);
          remoteStream.value = null;
        }
      }
    );
  };

  // 加入房间
  const joinRoom = async (roomId: string) => {
    console.log("加入房间");
    roomID.value = roomId;
    const result = await zego.value.loginRoom(roomID.value, token, {
      userID: userID.value,
      userName: userName.value,
    });
    console.log("加入房间结果:", result);
    isInRoom.value = true;
    return result;
  };

  // 1V1视频聊天功能 -----start------

  // 开始推流
  const startPublishing = async () => {
    // 创建本地流
    localStream.value = await zego.value.createStream({
      camera: {
        video: true,
        audio: true,
      },
    });

    // 获取视频元素并播放本地流
    const localVideo = document.getElementById(
      "localVideo"
    ) as HTMLVideoElement;
    if (localVideo) {
      localVideo.srcObject = localStream.value;
    }

    // 开始推流
    const streamID = `${userID.value}_stream`;
    await zego.value.startPublishingStream(streamID, localStream.value);
    console.log("开始推流:", streamID);
    isPublishing.value = true;
    return streamID;
  };

  // 停止推流
  const stopPublishing = async () => {
    if (localStream.value) {
      await zego.value.stopPublishingStream();
      localStream.value.getTracks().forEach((track) => track.stop());
      localStream.value = null;
      isPublishing.value = false;
    }
  };

  // 播放远程流
  const playRemoteStream = async (streamID: string) => {
    const remoteStream = await zego.value.startPlayingStream(streamID);
    const remoteVideo = document.getElementById(
      "remoteVideo"
    ) as HTMLVideoElement;
    if (remoteVideo) {
      remoteVideo.srcObject = remoteStream;
    }
    console.log("开始播放远程流:", streamID);
  };

  // 停止播放流
  const stopPlayStream = (streamID: string) => {
    zego.value.stopPlayingStream(streamID);
    const remoteVideo = document.getElementById(
      "remoteVideo"
    ) as HTMLVideoElement;
    if (remoteVideo) {
      remoteVideo.srcObject = null;
    }
    console.log("停止播放流:", streamID);
  };

  // 离开房间
  const leaveRoom = async () => {
    await stopPublishing();
    if (remoteStream.value) {
      stopPlayStream(remoteStream.value);
    }
    await zego.value.logoutRoom(roomID.value);
    roomID.value = "";
    isInit.value = false;
    isInRoom.value = false;
  };

  // 组件卸载时清理资源
  onUnmounted(() => {
    if (isInRoom.value) {
      leaveRoom();
    }
  });
  // 1V1视频聊天功能 -----end------

  //  直播功能 - 主播端 -----start------
  const startLive = async (
    roomID: string,
    userID: string,
    userName: string
  ) => {
    const kittoken = await generateToken(roomID, userID);

    await zego.value.loginRoom(roomID, kittoken, {
      userID,
      userName,
      role: "host", // 设置为主播角色
    });

    // 创建更高质量的流
    const localStream = await zego.value.createStream({
      camera: {
        video: {
          quality: 2, // 高清
          width: 1280,
          height: 720,
          frameRate: 15,
        },
        audio: true,
      },
    });

    // 获取视频元素并播放本地流
    const localVideo = document.getElementById("liveRoom") as HTMLVideoElement;
    if (localVideo) {
      localVideo.srcObject = localStream;
    }

    await zego.value.startPublishingStream(`live_${roomID}`, localStream);

    return localStream;
  };
  // 直播功能 - 观众端
  const watchLive = async (
    roomID: string,
    userID: string,
    userName: string
  ) => {
    const kittoken = await generateToken(roomID, userID);

    await zego.value.loginRoom(roomID, kittoken, {
      userID,
      userName,
      role: "audience", // 设置为观众角色
    });

    // 监听流新增事件
    zego.value.on(
      "roomStreamUpdate",
      (roomID: string, updateType: unknown, streamList: ZegoStream[]) => {
        if (updateType === "ADD") {
          streamList.forEach((stream) => {
            zego.value.startPlayingStream(stream.streamID);
          });
        }
      }
    );
  };

  // 消息服务
  // const emitter = mitt();
  // 初始化消息服务
  const initMessageService = async () => {
    if (!isInit.value) {
      throw new Error("SDK未初始化");
    }
    // 启用实时消息功能
    zego.value.enableNotifyWhenAppActive(true);
    // 设置消息回调
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    // zego.value.on(
    //   "IMRecvBroadcastMessage",
    //   (roomID: string, messageList: any[]) => {
    //     messageList.forEach((msg) => {
    //       emitter.emit("message", {
    //         sender: msg.fromUser.userName,
    //         content: msg.message,
    //         timestamp: msg.sendTime,
    //       });
    //     });
    //   }
    // );
  };
  // 发送广播消息
  const sendBroadcastMessage = async (message: string) => {
    if (!isInit.value) throw new Error("SDK未初始化");

    const result = await zego.value.sendBroadcastMessage(roomID.value, message);
    if (result.errorCode === 0) {
      return {
        sender: userName.value,
        content: message,
        timestamp: Date.now(),
      };
    }
    throw new Error(`发送失败: ${result.errorCode}`);
  };

  // 清理资源
  const destroyLive = async () => {
    if (zego.value) {
      await zego.value.logoutRoom();
      zego.value.destroyEngine();
      zego.value = null;
      isInit.value = false;
      isInRoom.value = false;
    }
  };

  return {
    zego,
    localStream,
    remoteStream,
    userID,
    userName,
    roomID,
    isInRoom,
    isPublishing,
    initSDK,
    joinRoom,
    startPublishing,
    stopPublishing,
    playRemoteStream,
    stopPlayStream,
    leaveRoom,
    startLive,
    watchLive,
    destroyLive,
    initMessageService,
    sendBroadcastMessage,
  };
}
